package service

import (
	"context"
	"fmt"
	"log"
	"net"

	"gitee.com/gldmmhh/bbs/config"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/bbs"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/bbs/postservice"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/title_service/titleservice"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/user"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/user/userservice"
	"github.com/cloudwego/kitex/client"
	"github.com/cloudwego/kitex/pkg/loadbalance"
	"github.com/cloudwego/kitex/server"
	"github.com/cloudwego/kitex/transport"
	"github.com/hashicorp/consul/api"
	consul "github.com/kitex-contrib/registry-consul"
)

var titleClient titleservice.Client // bbsAgent标题生成服务客户端
var postClient postservice.Client   // bbsAgent帖子生成服务客户端
var userClient userservice.Client   // bbsAgent用户生成服务客户端

// NewPostBusinessLogic 创建帖子业务逻辑实例
func initClient(cfg *config.Config) error {
	var err error
	r, err := consul.NewConsulResolver(cfg.Consul.Address)
	if err != nil {
		log.Printf("创建Consul解析器失败: %v", err)
		return err
	}

	// 使用Consul服务发现创建客户端
	titleClient, err = titleservice.NewClient("title_service",
		client.WithResolver(r), // 使用Consul服务发现
		client.WithLoadBalancer(loadbalance.NewWeightedBalancer()), // 负载均衡
		client.WithTransportProtocol(transport.GRPC))               // 使用gRPC协议
	if err != nil {
		log.Printf("初始化标题生成服务客户端失败: %v", err)
		return err
	}
	log.Println("标题生成服务客户端已通过Consul服务发现初始化")

	postClient, err = postservice.NewClient("post_service",
		client.WithResolver(r), // 使用Consul服务发现
		client.WithLoadBalancer(loadbalance.NewWeightedBalancer()), // 负载均衡
		client.WithTransportProtocol(transport.GRPC))               // 使用gRPC协议
	if err != nil {
		log.Printf("初始化帖子生成服务客户端失败: %v", err)
		return err
	}
	log.Println("帖子生成服务客户端已通过Consul服务发现初始化")

	userClient, err = userservice.NewClient("user_service",
		client.WithResolver(r), // 使用Consul服务发现
		client.WithLoadBalancer(loadbalance.NewWeightedBalancer()), // 负载均衡
		client.WithTransportProtocol(transport.GRPC))               // 使用gRPC协议
	if err != nil {
		log.Printf("初始化用户生成服务客户端失败: %v", err)
		return err
	}
	log.Println("用户生成服务客户端已通过Consul服务发现初始化")

	return nil
}

// UserServiceImpl 实现用户服务接口
type UserServiceImpl struct {
}

// NewUserService 创建用户服务实例
func NewUserService() *UserServiceImpl {
	return &UserServiceImpl{}
}

// GetUser 获取用户信息
func (s *UserServiceImpl) GetUser(ctx context.Context, req *user.GetUserRequest) (*user.GetUserResponse, error) {
	return GetUserInfo(req.UserId)
}

func (s *UserServiceImpl) Login(ctx context.Context, req *user.LoginRequest) (*user.LoginResponse, error) {
	return LoginLogic(ctx, req)
}

func (s *UserServiceImpl) Register(ctx context.Context, req *user.RegisterRequest) (*user.RegisterResponse, error) {
	return RegisterLogic(req.Username, req.Password)
}

// FollowUser 关注用户
func (s *UserServiceImpl) FollowUser(ctx context.Context, req *user.FollowUserRequest) (*user.FollowUserResponse, error) {
	return FollowUserLogic(req.UserId, req.FollowerId)
}

// GetFollowing 获取关注列表
func (s *UserServiceImpl) GetFollowing(ctx context.Context, req *user.GetFollowingRequest) (*user.GetFollowingResponse, error) {
	return GetFollowingLogic(req.UserId, int(req.Page), int(req.Size))
}

// PostServiceImpl 实现帖子服务接口
type PostServiceImpl struct{}

// NewPostService 创建帖子服务实例
func NewPostService(cfg *config.Config) *PostServiceImpl {
	return &PostServiceImpl{}
}

// GetUserPosts 获取用户帖子列表
func (s *PostServiceImpl) GetUserPosts(ctx context.Context, req *bbs.GetUserPostsRequest) (*bbs.GetUserPostsResponse, error) {
	return GetUserPostsLogic(req.UserId, int(req.Page), int(req.Size))
}

// GetPosts 获取帖子列表
func (s *PostServiceImpl) GetPosts(ctx context.Context, req *bbs.GetPostsRequest) (*bbs.GetPostsResponse, error) {
	return GetPostsLogic(int(req.Page), int(req.Limit), req.Sort, req.Order)
}

// GetPostDetail 获取帖子详情
func (s *PostServiceImpl) GetPostDetail(ctx context.Context, req *bbs.GetPostDetailRequest) (*bbs.GetPostDetailResponse, error) {
	// 这里暂时使用0作为用户ID，实际应该从请求中获取
	return GetPostDetailLogic(req.PostId, 0)
}

// LikePost 点赞帖子
func (s *PostServiceImpl) LikePost(ctx context.Context, req *bbs.LikePostRequest) (*bbs.LikePostResponse, error) {
	return LikePostLogic(req.PostId, req.LikerId)
}

// CancelLikePost 取消点赞
func (s *PostServiceImpl) CancelLikePost(ctx context.Context, req *bbs.CancelLikePostRequest) (*bbs.CancelLikePostResponse, error) {
	return CancelLikePostLogic(req.PostId, req.LikerId)
}

// SavePost 收藏帖子
func (s *PostServiceImpl) SavePost(ctx context.Context, req *bbs.SavePostRequest) (*bbs.SavePostResponse, error) {
	return SavePostLogic(req.PostId, req.SaverId)
}

// CancelSavePost 取消收藏
func (s *PostServiceImpl) CancelSavePost(ctx context.Context, req *bbs.CancelSavePostRequest) (*bbs.CancelSavePostResponse, error) {
	return CancelSavePostLogic(req.PostId, req.SaverId)
}

// CreatePost 创建帖子
func (s *PostServiceImpl) CreatePost(ctx context.Context, req *bbs.CreatePostRequest) (*bbs.CreatePostResponse, error) {
	return CreatePostLogic(req.Writer, req.Summary, req.Content)
}

// UpdatePost 更新帖子
func (s *PostServiceImpl) UpdatePost(ctx context.Context, req *bbs.UpdatePostRequest) (*bbs.UpdatePostResponse, error) {
	return UpdatePostLogic(req.PostId, req.Summary, req.Content)
}

// DeletePost 删除帖子
func (s *PostServiceImpl) DeletePost(ctx context.Context, req *bbs.DeletePostRequest) (*bbs.DeletePostResponse, error) {
	return DeletePostLogic(req.PostId, req.UserId)
}

// StartUserRPCServer 启动用户RPC服务
func StartUserRPCServer(port int, cfg *config.Config) {
	addr, _ := net.ResolveTCPAddr("tcp", fmt.Sprintf(":%d", port))
	svr := userservice.NewServer(NewUserService(), server.WithServiceAddr(addr))

	// 注册到Consul
	serviceID := fmt.Sprintf("user-rpc-service-%d", port)
	registerToConsul(cfg, serviceID, "user-rpc", port)

	log.Printf("用户RPC服务启动在端口 %d", port)
	err := svr.Run()
	if err != nil {
		log.Fatalf("用户RPC服务启动失败: %v", err)
	}
}

// StartPostRPCServer 启动帖子RPC服务
func StartPostRPCServer(port int, cfg *config.Config) {
	addr, _ := net.ResolveTCPAddr("tcp", fmt.Sprintf(":%d", port))
	svr := postservice.NewServer(NewPostService(cfg), server.WithServiceAddr(addr))

	// 注册到Consul
	serviceID := fmt.Sprintf("post-rpc-service-%d", port)
	registerToConsul(cfg, serviceID, "post-rpc", port)

	log.Printf("帖子RPC服务启动在端口 %d", port)
	err := svr.Run()
	if err != nil {
		log.Fatalf("帖子RPC服务启动失败: %v", err)
	}
}

// registerToConsul 注册服务到Consul
func registerToConsul(cfg *config.Config, serviceID, serviceName string, port int) {
	// 创建Consul客户端
	consulConfig := api.DefaultConfig()
	consulConfig.Address = cfg.Consul.Address
	client, err := api.NewClient(consulConfig)
	if err != nil {
		log.Printf("创建Consul客户端失败: %v", err)
		return
	}

	// 构建服务注册信息
	registration := &api.AgentServiceRegistration{
		ID:      serviceID,
		Name:    serviceName,
		Tags:    []string{"rpc", "kitex"},
		Port:    port,
		Address: "10.129.20.176",
		Check: &api.AgentServiceCheck{
			TCP:                            fmt.Sprintf("10.129.20.176:%d", port),
			Timeout:                        cfg.Consul.HealthCheckTimeout,
			Interval:                       cfg.Consul.HealthCheckInterval,
			DeregisterCriticalServiceAfter: cfg.Consul.DeregisterCriticalAfter,
		},
	}

	// 注册服务
	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		log.Printf("注册服务到Consul失败: %v", err)
	} else {
		log.Printf("服务 %s (ID: %s) 已注册到Consul，健康检查: TCP %s:%d", serviceName, serviceID, "localhost", port)
	}
}

// deregisterFromConsul 从Consul注销服务
func deregisterFromConsul(cfg *config.Config, serviceID string) {
	// 创建Consul客户端
	consulConfig := api.DefaultConfig()
	consulConfig.Address = cfg.Consul.Address
	client, err := api.NewClient(consulConfig)
	if err != nil {
		log.Printf("创建Consul客户端失败: %v", err)
		return
	}

	// 注销服务
	err = client.Agent().ServiceDeregister(serviceID)
	if err != nil {
		log.Printf("从Consul注销服务失败: %v", err)
	} else {
		log.Printf("服务 %s 已从Consul注销", serviceID)
	}
}
